import React from "react";
import Relay from "react-relay";

import {Modal,Input,InputNumber,message,Button} from 'antd';

import FileUpData from '../components/FileUpDataPro'  //上传附件

import GetQiNiuToken from "../mutation/FindSewRawListMutation"  //上传图片获取token

import orderTaxRebateSendInvoice  from '../mutation/orderTaxRebateSendInvoice';

import Config from "../../../util/Config"

export default class B extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            vis:false,
            data:{},   // 由上层组件赋予的data数据

            fileList:[],  //上传文件列表
            numValue:1,   // 发票张数 [value]
            courierEnter:"", //快递公司
            invoiceText:"",  //发票单号
        };

        this.fileAccept = ".rar,.zip,.jpg,.jpeg,.png,.bmp,.gif";

        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.clear = this.clear.bind(this);
        this.addFileItem = this.addFileItem.bind(this);

        this.handleNumberChange = this.handleNumberChange.bind(this);
        this.handleNumberBlur = this.handleNumberBlur.bind(this);  // 失去焦点
    }

    componentWillMount(){
        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        });
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败")
                }
            }
        );
    }
    componentDidMount(){}

    // 验证
    regTest(text) {
        const r = /[^ ]/g;
        if (r.test(text)) {
            return true
        }
        return false;
    }

    // 数据发送
    requestHttpPost(obj){
        Relay.Store.commitUpdate(
            new orderTaxRebateSendInvoice({...obj}),{
                onFailure:(err)=>{
                    message.error("网络连接错误，请重试")
                },
                onSuccess:(res)=>{
                        const d = res.orderTaxRebateSendInvoice.orderTaxRebateSendInvoice;
                        if(d.errorCode != "0"){ message.error(d.value); return; }
                        message.success("保存成功");
                        this.props.requestInfo(1,10);  //刷新父组件列表
                        this.clear();               //清空状态
                }
            }
        )
    }

    onOk(){
        const cour = this.state.courierEnter,
               invo = this.state.invoiceText,
               invonum = this.state.numValue,
               fileList = this.state.fileList;

        const Id = sessionStorage.getItem("msUid"),
               Name = sessionStorage.getItem("msUserName");

        if( cour && invo && invonum && fileList.length != 0 ){
            if(!this.regTest(cour) && !this.regTest(invo)) { message.error("格式不正確，请检查"); return; }

            if(fileList[0].status != "done"){ message.info("请等待文件上传完成"); return; }

            // 发送数据Post
            this.requestHttpPost({
                orderId:this.state.data.orderId,   //订单号
                sendStatus:this.props.status,   //props. 状态
                sendUserName:Name,  //后台操作人姓名
                sendUser:Id,

                invoiceNum:invonum,  //发票数量
                expressName:cour,   //快递公司
                expressSheet:invo,  // 快递单号
                invoiceFileJson:JSON.stringify(fileList)   // file附件
            })
        }else{
            message.error("必填项不能为空!");
        }
    }

    onCancel(){
        this.clear();
    }

    clear(){
        this.setState({
            vis:false,
            data:{},   // 由上层组件赋予的data数据
            fileList:[],  //上传文件列表
            numValue:1,   // 发票张数 [value]
            courierEnter:"", //快递公司
            invoiceText:"",  //发票单号
        })
    }

    // 数字
    handleNumberChange(value){
        this.setState({numValue:value})
    }

    handleNumberBlur(){
        let value = this.state.numValue;
        if(typeof value === "number"){ value = value.toString(); }
        if(value.indexOf(".") !== -1){
            const v = value.slice(0,value.indexOf("."));
            this.setState({
                numValue:v
            })
        }
    }

    // 快递公司与发票单号 change
    CourierInvoiceEnter(e,key){
        // 判断快递公司或发票单号input，分别做处理
        const type = key == "1" ? "courierEnter" : "invoiceText";

        this.setState({[type]:e.target.value});
    }

    // 文件超出数量提示[伪事件]
    handleClickSelf(){message.warning("附件最多允许上传5个")}

    fileBeforeload(e){
        // ".rar,.zip,.jpg,.jpeg,.png,.bmp,.gif";
        let Reg = [".rar",".zip", ".jpg", ".jpeg", ".png",".bmp",".gif"];  //格式
        function formatTest(reg,name){
            if(!reg || !name){ return; }
            const D = Array.from(reg),
                N = name.toLowerCase();
            for(let i in D){
                const I = D[i].toLowerCase();
                if(N.lastIndexOf(I) !== -1){
                    return true
                }
            }
            return false;
        }

        if(!!e.name){
            if(formatTest(Reg,e.name) && (e.size/1024/1024) < 50) {
                return true
            }else{
                message.error("文件格式错误或超过大小限制，请重新选择");
                return false;
            }
        }
    }
    /**
     * Created by liutong on 17/6/17.
     */

    pingImg(url, callback) {
        const img = new Image();
        let done;
        const finish = (status) => {
            if (!done) {
                done = true;
                img.src = '';
                callback(status);
            }
        };
        img.onload = () => finish('responded');
        img.onerror = () => finish('error');
        img.src = url;
        return setTimeout(() => finish('timeout'), 1500);
    }

    FileBase64(img,callback){
        const f = new FileReader();
        f.addEventListener("load",function(){
            callback(this.result);
        });
        f.readAsDataURL(img);
    }

    addFileItem(file,fileList){
        if (file.status === "uploading") {
            if (file.type.indexOf("image") !== -1) {
                this.FileBase64(file.originFileObj, (result) => {
                    this.pingImg(result, (status) => {
                        if (status === "responded") {
                            this.setState({fileList: fileList});
                        } else {
                            message.error("上传失败或支持的类型");
                        }
                    })
                })
            }else{
                this.setState({fileList: fileList});
            }
        }else if(file.status === "done"){
            this.setState({fileList:fileList});
        }else if(file.status === "removed"){
            this.setState({fileList:fileList});
        }
    }

    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload,
        accept:this.fileAccept,
    };


    render() {
        const {vis,token,data,fileList,numValue,courierEnter,invoiceText} = this.state;
        const {status} = this.props;
        const title = status == "1" ? "上传发票" : "查看发票";

        let info = data || {};

        const fileArr =  info.invoiceFileJson ? JSON.parse(info.invoiceFileJson) :[];

        return(<Modal
                    title={title}
                    visible={vis}
                    onCancel={this.onCancel}
                    onOk={this.onOk}
                    footer={
                        status == "1" ?
                        <div>
                            <Button onClick={this.onCancel}> 取消 </Button>
                            <Button onClick={this.onOk}> 确定 </Button>
                        </div> : null
                    }
                >
                    <div className="rebatemanage_invoiceModal">
                        <header className="rebatemanage_invoiceModal_header">
                            <p key="partAAddress">  邮寄地址：<span> { info.partAAddress || "-" } </span> </p>
                            <p key="partAUserName"> 业务员： <span>  {info.partAUserName} - </span>  {info.partAPhone} </p>
                        </header>

                        <div className="rebatemanage_modal_item" key="numValue">
                            {status == "1" && <i className="rebatemanage_star"> </i>}
                            <span> 发票张数： </span>
                            {
                                status == "1" ? <InputNumber min={1} max={10000} step={1} value={numValue} size="small"
                                                             onChange={this.handleNumberChange} onBlur={this.handleNumberBlur}
                                /> :
                                    <span> {info.invoiceNum} </span>
                            }
                        </div>

                        <div className="rebatemanage_modal_item" key="courierEnter">
                            {status == "1" && <i className="rebatemanage_star"> </i>}
                            <span> 快递公司： </span>
                            {
                                status == "1" ? <Input type="text" size="small" maxLength="50" value={courierEnter} onChange={(e)=>{this.CourierInvoiceEnter(e,"1")}} /> :
                                    <span> {info.expressName} </span>
                            }

                        </div>

                        <div className="rebatemanage_modal_item" key="invoiceText">
                            {status == "1" && <i className="rebatemanage_star"> </i>}
                            <span> 快递单号： </span>
                            {
                                status == "1" ?  <Input type="text" size="small"  maxLength="50" value={invoiceText} onChange={(e)=>{this.CourierInvoiceEnter(e,"2")}} /> :
                                    <span> {info.expressSheet} </span>
                            }
                        </div>

                        <div className="rebatemanage_modal_item" key="fileUploadPlugin">
                            {status == "1" && <i className="rebatemanage_star"> </i>}
                            <span> 发票附件：</span>
                            {
                                status == "1" ? <div className="rebatemanage_modal_viewFile">
                                    {/*上传文件*/}
                                    <FileUpData
                                        filePlugin={this.fileUploadPlugin}
                                        fileList={fileList}
                                        callBack={this.addFileItem}   //回调，第一个参数为file,第二个参数为本地name
                                        token={token}
                                        isShowTrigger={fileList.length < 5}
                                        handleClickSelf={this.handleClickSelf}
                                    />
                                </div>: <ul className="rebatemanage_modal_viewFile">
                                    {
                                        Array.isArray(fileArr) && fileArr.map((item,index)=>
                                            <li key={index}><a href={`${Config.qiuniu+item.response.key}?attname=${item.name}`} title={item.name} download > {item.name} </a></li>
                                        )
                                    }
                                </ul>
                            }
                        </div>
                    </div>

                    <footer>
                        {
                            status == "1" && <p className="rebatemanage_modal_item_alarm">（附件最大50M，支持格式：RAR,ZIP,JPG,PNG,BMP,GIF） </p>
                        }
                    </footer>
                </Modal>

        )
    }
}